/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MainPackage;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;


import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
/**
 *
 * @author admin
 */


public class XML_Creator {

    private final int INITIAL = 0;
    private final int REFRESH = 10;

    ArrayList<UnifiedFormat> myData;
    Document dom;
    String filename = "createtest.xml";

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);


    public XML_Creator(UnifiedFormat uf) {



            //create a list to hold the data
            myData  = new ArrayList<UnifiedFormat>();

            //initialize the list
            loadData(uf);

            //Get a DOM object
            createDocument();
	}

    public void runExample(){
    


    
        System.out.println("-----Begin-XML-Create--------");
        System.out.println("Started .. ");
        createDOMTree();
        try {
            printToFile();
        } catch (IOException ex) {
            Logger.getLogger(XML_Creator.class.getName()).log(Level.SEVERE, null, ex);
        }
        deleteFirstLine(filename);
        System.out.println("Generated file '" + filename + "' successfully.");
        Upload.establishConnection(filename);





    }

    private void loadData(UnifiedFormat uf){

        myData.add(uf);

    }

    private void createDocument() {

		//get an instance of factory
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
		//get an instance of builder
		DocumentBuilder db = dbf.newDocumentBuilder();

		//create an instance of DOM
		dom = db.newDocument();

		}catch(ParserConfigurationException pce) {
			//dump it
			System.out.println("Error while trying to instantiate DocumentBuilder " + pce);
			System.exit(1);
		}

	}

    private void createDOMTree(){

		//Erstelle das Wurzel-Element
		Element rootEle = dom.createElement("ContinuityOfCareRecord");
                rootEle.setAttribute("xmlns", "urn:astm-org:CCR");
		dom.appendChild(rootEle);

                //Erstelle 1. Kind-Element CCRDocumentObjectID
                Element ccrdocEle = dom.createElement("CCRDocumentObjectID");
                Text ccrdocText = dom.createTextNode("doc");
                ccrdocEle.appendChild(ccrdocText);
                rootEle.appendChild(ccrdocEle);

                //Erstelle Kind-Element Language
                Element langEle = dom.createElement("Language");
                Element langTextEle = dom.createElement("Text");
                Text langtext = dom.createTextNode("English");
                langTextEle.appendChild(langtext);
                langEle.appendChild(langTextEle);
                rootEle.appendChild(langEle);

                //Erstelle Kind-Element Version
                Element versEle = dom.createElement("Version");
                Text verstext = dom.createTextNode("V1.0");
                versEle.appendChild(verstext);
                rootEle.appendChild(versEle);

                //Erstelle Kind-Element DateTime
                Element datetimeEle = dom.createElement("DateTime");
                Element datetimeExactDateTime = dom.createElement("ExactDateTime");
                Text exactDTtext = dom.createTextNode(myData.get(0).getCollectionStartDate());
                datetimeExactDateTime.appendChild(exactDTtext);
                datetimeEle.appendChild(datetimeExactDateTime);
                rootEle.appendChild(datetimeEle);

                //Erstelle Kind-Element Patient
                Element patientEle = dom.createElement("Patient");
                Element patientActorID = dom.createElement("ActorID");
                Text patientActorIDtext = dom.createTextNode("Patient");
                patientActorID.appendChild(patientActorIDtext);
                patientEle.appendChild(patientActorID);
                rootEle.appendChild(patientEle);

                //Erstelle Kind-Elemente ab Body
                Element bodyEle = dom.createElement("Body");
                Element resultsEle = dom.createElement("Results");
               
              
                

		//Test Results einlesen
		Iterator it  = myData.iterator();
		while(it.hasNext()) {
			UnifiedFormat uf = (UnifiedFormat)it.next();
			//Für jedes Result wird ein result Element angelegt
			Element resultEle = createUFElement(uf);
			resultsEle.appendChild(resultEle);
		}
               
                bodyEle.appendChild(resultsEle);
                rootEle.appendChild(bodyEle);


	}

    private Element createUFElement(UnifiedFormat uf){

                Element resultEle = dom.createElement("Result");

                Element testEle = dom.createElement("Test");

                Element testdatetimeEle = dom.createElement("DateTime");
                Element testdatetimeTypeEle = dom.createElement("Type");
                Element testdatetimeTypeTextEle = dom.createElement("Text");
                Element testdatetimeExactDTEle = dom.createElement("ExactDateTime");
                Text testDTTypetext = dom.createTextNode("Collection start date");
                Text testDTExactDTtext = dom.createTextNode(uf.getexactDateTimeString());
                testdatetimeTypeTextEle.appendChild(testDTTypetext);
                testdatetimeTypeEle.appendChild(testdatetimeTypeTextEle);
                testdatetimeExactDTEle.appendChild(testDTExactDTtext);
                testdatetimeEle.appendChild(testdatetimeTypeEle);
                testdatetimeEle.appendChild(testdatetimeExactDTEle);
                testEle.appendChild(testdatetimeEle);

                Element descriptionEle = dom.createElement("Description");
                Element descriptioncodeEle = dom.createElement("Code");
                Element descriptioncodevalueEle = dom.createElement("Value");
                Element descriptioncodingsystemEle = dom.createElement("CodingSystem");
                Text codevaluetext = dom.createTextNode(uf.getCodingValue());
                Text codingsystemtext = dom.createTextNode(uf.getCodingSystem());
                descriptioncodingsystemEle.appendChild(codingsystemtext);
                descriptioncodevalueEle.appendChild(codevaluetext);
                descriptioncodeEle.appendChild(descriptioncodevalueEle);
                descriptioncodeEle.appendChild(descriptioncodingsystemEle);
                descriptionEle.appendChild(descriptioncodeEle);
                testEle.appendChild(descriptionEle);

                Element testresultEle = dom.createElement("TestResult");
                Element testresultvalueEle = dom.createElement("Value");
                Element testresultunitsEle = dom.createElement("Units");
                Element testresultunitEle = dom.createElement("Unit");
                Text testresultvaluetext = dom.createTextNode(uf.getTestResultValue());
                Text testresultunittext = dom.createTextNode(uf.getTestResultUnit());
                testresultunitEle.appendChild(testresultunittext);
                testresultvalueEle.appendChild(testresultvaluetext);
                testresultunitsEle.appendChild(testresultunitEle);
                testresultEle.appendChild(testresultvalueEle);
                testresultEle.appendChild(testresultunitsEle);
                testEle.appendChild(testresultEle);

                Element normalresultEle = dom.createElement("NormalResult");
                Element normalresultnormalEle = dom.createElement("Normal");
                Element normalresultdescriptionEle = dom.createElement("Description");
                Element normalresultdescriptiontextEle = dom.createElement("Text");
                Text normalresultdescriptiontext = dom.createTextNode(uf.getNormalResult());
                normalresultdescriptiontextEle.appendChild(normalresultdescriptiontext);
                normalresultdescriptionEle.appendChild(normalresultdescriptiontextEle);
                normalresultnormalEle.appendChild(normalresultdescriptionEle);
                normalresultEle.appendChild(normalresultnormalEle);
                testEle.appendChild(normalresultEle);
                
                Element sourceEle = dom.createElement("Source");
                Element sourceactorEle = dom.createElement("Actor");
                Element sourceactorIDEle = dom.createElement("ActorID");
                Element sourceatorroleEle = dom.createElement("ActorRole");
                Element sourceactorroletextEle = dom.createElement("Text");
                Text sourceactoridtext = dom.createTextNode(uf.getActorID());
                Text sourceacotrroletext = dom.createTextNode(uf.getActorRole());
                sourceactorroletextEle.appendChild(sourceacotrroletext);
                sourceactorIDEle.appendChild(sourceactoridtext);
                sourceatorroleEle.appendChild(sourceactorroletextEle);
                sourceactorEle.appendChild(sourceactorIDEle);
                sourceactorEle.appendChild(sourceatorroleEle);
                sourceEle.appendChild(sourceactorEle);
                testEle.appendChild(sourceEle);

                resultEle.appendChild(testEle);

                return resultEle;

	}

    private void printToFile() throws IOException{

                FileOutputStream fos = null;

		try
		{
			//print
			OutputFormat format = new OutputFormat(dom);
			format.setIndenting(true);

			//to generate output to console use this serializer
			//XMLSerializer serializer = new XMLSerializer(System.out, format);

                         fos =	new FileOutputStream(new File(filename));
			//to generate a file output use fileoutputstream instead of system.out
			XMLSerializer serializer = new XMLSerializer(fos, format);

			serializer.serialize(dom);

		} catch(IOException ie) {
		    ie.printStackTrace();
		} finally{
                    fos.close();
                }
	}

    private void deleteFirstLine(String file) {
        PrintWriter pw = null;

        try {
            File inFile = new File(file);
            if (!inFile.isFile()) {
                System.out.println("Parameter is not an existing file");
                return;
            }
            File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            pw = new PrintWriter(new FileWriter(tempFile));
            String line = null;
            //Read from the original file and write to the new
            //unless content matches data to be removed.
            int counter = 0;
            while((line = br.readLine()) != null) {

                if (counter++ != 0) {
                    pw.println(line);
                    pw.flush();
                }
            }
            pw.close();
            br.close();
            //Delete the original file

            if (!inFile.delete()) {
                System.out.println("Could not delete file");
                return;
            }
            //Rename the new file to the filename the original file had.
            if (!tempFile.renameTo(inFile)) {
                System.out.println("Could not rename file");
            }
        } catch (IOException ex) {
            Logger.getLogger(XML_Creator.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            pw.close();
        }


    }    


}
